#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>

//#define SERVER_IP "127.0.0.1"
#define SERVER_IP "192.168.1.75"
#define PORT 8080
#define BUFFER_SIZE 1024

int sockfd;
int uid = -1;
int running = 1;

/* 接收消息线程 */
void *recv_thread(void *arg) {
    char buffer[BUFFER_SIZE];
    while (running) {
        int recv_len = recv(sockfd, buffer, BUFFER_SIZE, 0);
        if (recv_len > 0) {
            buffer[recv_len] = '\0';
            
            /* 解析用户ID */
            if (uid == -1 && strstr(buffer, "用户ID是")) {
                sscanf(buffer, "你的用户ID是：%d", &uid);
                printf("\n=== 成功连接！你的ID: %d ===\n", uid);
            } else {
                printf("\n%s\n> ", buffer);
                fflush(stdout);
            }
        } else if (recv_len == 0) {
            printf("\n服务器已关闭连接\n");
            running = 0;
        } else {
            perror("接收错误");
            running = 0;
        }
    }
    return NULL;
}

int main() {
    struct sockaddr_in serv_addr;
    pthread_t tid;

    /* 创建套接字 */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("套接字创建失败");
        exit(EXIT_FAILURE);
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    /* 转换IP地址 */
    if (inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr) <= 0) {
        perror("地址转换错误");
        exit(EXIT_FAILURE);
    }

    /* 连接服务器 */
    if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("连接失败");
        exit(EXIT_FAILURE);
    }

    /* 启动接收线程 */
    if (pthread_create(&tid, NULL, recv_thread, NULL) != 0) {
        perror("线程创建失败");
        exit(EXIT_FAILURE);
    }

    printf("输入命令：\n");
    printf("群聊消息 -> 直接输入内容\n");
    printf("私聊消息 -> /私聊 目标UID 消息内容\n");
    printf("退出程序 -> exit\n\n");

    char buffer[BUFFER_SIZE];
    while (running) {
        printf("> ");
        fflush(stdout);
        
        if (fgets(buffer, BUFFER_SIZE, stdin) == NULL) {
            break;
        }
        
        buffer[strcspn(buffer, "\n")] = '\0';  // 去除换行符

        if (strcmp(buffer, "exit") == 0) {
            printf("正在安全退出...\n");
            running = 0;
            
            /* 优雅关闭连接 */
            shutdown(sockfd, SHUT_WR);
            
            /* 等待服务器确认 */
            char temp[BUFFER_SIZE];
            while (recv(sockfd, temp, BUFFER_SIZE, 0) > 0);
            
            break;
        }

        /* 发送消息 */
        if (send(sockfd, buffer, strlen(buffer), 0) < 0) {
            perror("发送失败");
            break;
        }
        
        usleep(100000);  // 防止输入提示符错位
    }

    /* 清理资源 */
    close(sockfd);
    printf("=== 连接已关闭 ===\n");
    return 0;
}
